﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using IBatisNet.DataMapper;
using Ivi.Visa;
using Modbus.Device;
using Modbus.Message;
using Modbus.Utility;
using pageHelper;
using TempHum.service;
using temphumHis;
using temphumProp;
using temphumState;
using WinFormDemo.Helper;

namespace TempHum
{
    public partial class Form1 : Form
    {
        temphumPropdao dao;
        temphumProperty selectItem;
        visaUtil util = new visaUtil();
        SerialPort serialPort = null;
        SerialPort productserialPort = null;
        int selectIndex;//参数选择项
        RadioButton testingRadio;
        Dictionary<string, string> codes;//初始化产品端口码
        Dictionary<string, string> codeIndexes;
        ushort selectedCodeindex;
        IMessageBasedSession Tempsession;
        IMessageBasedSession HumSession;
        Boolean[]  radioStates = new Boolean[96];
        ModbusMaster boardmaster;
        ModbusMaster productmaster;
        bool isBreak = false;
        int waitTime = 8000;
        int curwaitTime = 8000;
        int volwaitTime = 4000;
        float X;
        float Y;
        public Form1()
        {
            dao = new temphumPropdao(Mapper.Instance());
            InitializeComponent();
            bindCbox(0);
            initProductCode();
            try
            {
                var resources = visaUtil.manager.Find("(ASRL|GPIB|TCPIP|USB)?*INSTR");
                foreach (var s in resources)
                {
                    comboBox2.Items.Add(s);
                    comboBox3.Items.Add(s);
                }
                comboBox2.SelectedIndex = 0;
                comboBox3.SelectedIndex = 0;
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
            comboBox4.Items.AddRange(SerialPort.GetPortNames());
            if (comboBox4.Items.Count > 0)
            {
                comboBox4.SelectedIndex = 0;
            }
            comboBox5.Items.AddRange(SerialPort.GetPortNames());
            if (comboBox5.Items.Count > 0) {
                comboBox5.SelectedIndex = 0;
            }                          
        }
        public delegate void updateTempValue(string value);
        public delegate void updateButtonText(Button btn,string txt);
        public delegate void updateHumValue(string value);
        public updateTempValue tempvalue;
        public updateHumValue humvalue;
        public void updateTempValueMethod(string value)
        {
            this.textBox3.Text = value;
        }
        public void updateButtonTextMethod(Button btn, string txt)
        {
            btn.Text = txt;
        }
        public void updateHumValueMethod(string value)
        {
            this.textBox4.Text = value;
        }
        public delegate void updateButtonEnable(Button button,Boolean enable);
        public updateButtonEnable btnenable;
        public updateButtonText btntxt;
        public void updateButtonEnableMethod(Button button, Boolean enable)
        {
            button.Enabled = enable;
        }
        public delegate void updateButtonState(string key, string value, string state);
        public updateButtonState update;
        public void updateMethod(string key, string value,string state)
        {
            if (key != null) {
                this.textBox2.Text = key;
            }
            if (value != null) {
                textBox1.Text = value;
            }        
            this.toolStripStatusLabel2.Text = state;
        }
        public delegate void updateGridData(ArrayList list);
        public updateGridData updateData;
        public void updateGridMethod(ArrayList list)
        {
            Console.WriteLine(333);
            dataGridView1.DataSource = list;
            dataGridView1.AutoGenerateColumns = false;
            // dataGridView1.AllowUserToResizeColumns = true;
            if (dataGridView1.Columns.Contains("id"))
            {
                dataGridView1.Columns["id"].Visible = false;
            }
            if (dataGridView1.Columns.Contains("testcount"))
            {
                dataGridView1.Columns["testcount"].Visible = false;
            }
            if (dataGridView1.Columns.Contains("producttype"))
            {
                dataGridView1.Columns["producttype"].Visible = false;
            }
            if (selectItem.producttype == 1)
            {
                Console.WriteLine(1111);
                if (dataGridView1.Columns.Contains("hum"))
                {
                    dataGridView1.Columns["hum"].Visible = false;
                }
                if (dataGridView1.Columns.Contains("humread"))
                {
                    dataGridView1.Columns["humread"].Visible = false;
                }
                if (dataGridView1.Columns.Contains("humpoint"))
                 {
                     dataGridView1.Columns["humpoint"].Visible = false;
               }
                //dataGridView1.Columns["humpoint"].Visible = false;
                if (dataGridView1.Columns.Contains("humdiv"))
                {
                    dataGridView1.Columns["humdiv"].Visible = false;
                }
            }
            else {
                if (dataGridView1.Columns.Contains("hum"))
                {
                    dataGridView1.Columns["hum"].Visible = true;
                }
                if (dataGridView1.Columns.Contains("humread"))
                {
                    dataGridView1.Columns["humread"].Visible = true;
                }
                if (dataGridView1.Columns.Contains("humpoint"))
                {
                    dataGridView1.Columns["humpoint"].Visible = true;
                }
                if (dataGridView1.Columns.Contains("humdiv"))
                {
                    dataGridView1.Columns["humdiv"].Visible = true;
                }
            }
            dataGridView1.Refresh();        }
        private void Form1_Load(object sender, EventArgs e)
        {
            this.Resize += new System.EventHandler(this.Form1_Resize);
            X = this.Width;
            Y = this.Height;
            ResizeForm.setTag(this);
            timer1.Interval = 1000;
            timer1.Start();
            update = new updateButtonState(updateMethod);
            updateData = new updateGridData(updateGridMethod);
            tempvalue = new updateTempValue(updateTempValueMethod);
            humvalue = new updateHumValue(updateHumValueMethod);
            btnenable = new updateButtonEnable(updateButtonEnableMethod);
            btntxt = new updateButtonText(updateButtonTextMethod);
        }
       
        private void Form1_Closed(object sender, EventArgs e)
        {
            visaUtil.closesession(HumSession);
            visaUtil.closesession(Tempsession);
            if (productserialPort != null) {
                productserialPort.Dispose();
            }
            if (productmaster != null) {
                productmaster.Dispose();
            }
            if (serialPort != null) {
                serialPort.Dispose();
            }
            if (boardmaster != null) {
                boardmaster.Dispose();
            }
            
        }
 
        private void groupBox4_PaintChanged(object sender, PaintEventArgs e)
        {
            e.Graphics.Clear(this.BackColor);
        }
        private void label2_Click(object sender, EventArgs e)
        {

        }
        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            selectItem = null;
            selectItem = (temphumProperty)this.comboBox1.SelectedItem;
            selectIndex = this.comboBox1.SelectedIndex;
            Console.WriteLine(selectItem.templower);
            loadData(selectItem);

        }


        private void radioButton1_CheckedChanged(object sender, EventArgs e)
        {
            if (radioButton1.Checked) {
                if (selectItem == null)
                {
                    selectItem = new temphumProperty();
                }
                selectItem.outtype = 0;
                selectItem.other = comboBox6.SelectedIndex == 0 ? "5" : "10";            // richTextBox8.Visible = true;
                label10.Text = "V";
                label12.Text = "V";
                label9.Visible = true;
                comboBox6.Visible = true;
            }
            
        }
        private int getcodesCount() {
            int count = 0;
            foreach (var item in codes)
            {
                if (item.Value != "")
                {
                    count++;
                }
            }
            return count;
        }
        private void button1_Click(object sender, EventArgs e)
        {
            logHelper.WriteLog("开始批量测试！");
            // button1.Enabled = false;
            button2.Enabled = false;
            if (numericUpDown1.Text == "")
            {
                MessageBoxEx.Show("请输入测试数量！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button2);
                button1.Enabled = true;
                button2.Enabled = true;
                return;
            }
            if (getcodesCount() != numericUpDown1.Value)
            {
                MessageBoxEx.Show("请检查数量是否正确！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button2);
                button1.Enabled = true;
                button2.Enabled = true;
                return;
            }
            if (!checkparam())
            {
                MessageBoxEx.Show("请检查参数！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button2);
                button1.Enabled = true;
                button2.Enabled = true;
                return;
            }
            if (button1.Text == "中断测试")
            {
                isBreak = true;
                this.BeginInvoke(update, null, null, "中断测试中！！");
                return;
            }
            else {
                button1.Text = "中断测试";
                isBreak = false;
            }
                  Thread thread = new Thread(new ThreadStart(delegate {
                     ArrayList list = new ArrayList();
                     foreach (var item in codes)
                {
                    if (item.Value != "")
                    {                      
                        this.BeginInvoke(update,codeIndexes[item.Key], item.Value,"端口"+ codeIndexes[item.Key]+"----开始测试！");
                        temphumHisData historydata = new temphumHisData();
                        historydata.id = Guid.NewGuid().ToString();
                        historydata.serialnumber = item.Value;
                        historydata.testport = codeIndexes[item.Key];
                        historydata.producttype = selectItem.producttype;
                        historydata.temppoint = selectItem.temppoint;
                       Boolean isPass = true;
                             if (selectItem.outtype == 0)
                             {
                                  waitTime = volwaitTime;
                                  historydata.testtype = "电压" + selectItem.other;
                             }
                             if (selectItem.outtype == 2)
                             {
                                 historydata.testtype = "RS485";
                             }
                             if (selectItem.outtype == 1)
                             {
                                  waitTime = curwaitTime;
                                  historydata.testtype = "电流";
                             }
                              try
                              {
                                  var readMsgReq = ModbusMessageFactory.CreateModbusRequest(modbusUtil.getSingleCoilMessage(Convert.ToInt16(codeIndexes[item.Key]), true));
                                  //获取响应报文
                                  var writeSingleCoilsRes = boardmaster.ExecuteCustomMessage<WriteSingleCoilRequestResponse>(readMsgReq);
                                  Thread.Sleep(waitTime);
                              }
                              catch (Exception e1)
                              {
                                  MessageBoxEx.Show("请检查切换版通讯是否正常！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button2);
                                  if (this.IsHandleCreated)
                                  {
                                      this.BeginInvoke(btnenable, button2, true);
                                      this.BeginInvoke(btntxt, button1, "批量测试");
                                  }
                                  return;
                              }
                              testingRadio = (RadioButton)this.Controls.Find(item.Key, true)[0];
                        testingRadio.BackColor = Color.Blue;
                              //testingRadio.Refresh();
                              float[] sumTemp = new float[5];
                              float[] sumHum = new float[5];
                              float[] sumTempRead = new float[5];
                              float[] sumHumRead = new float[5];
                              for (int i = 1; i <= 5; i++)
                              {
                                  string conf = "VOLT:DC " + selectItem.other;
                                  if (selectItem.outtype == 1)
                                  {
                                      conf = "CURR:DC";
                                  }
                                  if (selectItem.producttype == 0)
                                  { //温湿度类型

                                      float[] hum = readHumValue(conf);
                                      //float[] hum = { 20.02f, 2.4f };
                                      if (hum == null)
                                      {
                                          this.BeginInvoke(btnenable, button2, true);
                                          this.BeginInvoke(btntxt, button1, "批量测试");
                                          return;
                                      };
                                      Console.WriteLine("hum[1]:" + hum[1]);
                                      sumHum[i - 1] = hum[0];
                                      sumHumRead[i - 1] = hum[1];
                                      this.BeginInvoke(humvalue, hum[1].ToString());
                                  }
                                  float[] temp = readTempValue(conf);
                                  //float[] temp = { 20.01f, 2.4f };
                                  if (temp == null)
                                  {
                                      this.BeginInvoke(btnenable, button2, true);
                                      this.BeginInvoke(btntxt, button1, "批量测试");
                                      return;
                                  };
                                  sumTemp[i - 1] = temp[0];
                                  sumTempRead[i - 1] = temp[1];
                                  Console.WriteLine("temp[1]:" + temp[1]);
                                  this.BeginInvoke(tempvalue, temp[1].ToString());
                              }
                              Array.Sort(sumTemp);
                              Array.Sort(sumTempRead);
                              historydata.testtime = DateTime.Now;
                              historydata.tempread = sumTempRead[2];
                              historydata.temp = sumTemp[2];
                              historydata.tempdiv = (sumTemp[2]) - selectItem.temppoint;
                              if (Math.Abs((float)historydata.tempdiv) > selectItem.tempprecision) isPass = false;
                              if (selectItem.producttype == 0)
                              {
                                  Array.Sort(sumHum);
                                  Array.Sort(sumHumRead);
                                  historydata.humpoint = selectItem.humpoint;
                                  historydata.hum = sumHum[2];
                                  historydata.humdiv = (sumHum[2]) - selectItem.humpoint;
                                  historydata.humread = sumHumRead[2];
                                  if (Math.Abs((float)historydata.humdiv) > selectItem.humprecision) isPass = false;
                              }
                              if (!isPass)
                             {
                                 historydata.result = "NG";
                                 testingRadio.BackColor = Color.Red;
                             }
                             else
                             {
                                 historydata.result = "PASS";
                                 testingRadio.BackColor = Color.Green;
                             }
                             list.Add(historydata);                         
                             dao.saveHistoryData(historydata);
                             saveProductState(testingRadio);
                             this.BeginInvoke(update, codeIndexes[item.Key], item.Value, "端口" + codeIndexes[item.Key] + "----结束测试！");                        
                         }
                          if (isBreak)
                          {
                              isBreak = false;
                              this.BeginInvoke(btntxt, button1, "批量测试");
                              this.BeginInvoke(update, null, null, "中断完成！！");
                              break;                           
                          }
                      }
                     this.BeginInvoke(updateData, list);
                     this.BeginInvoke(update, null, null, "批量测试结束！");
                     this.BeginInvoke(btntxt, button1, "批量测试");
                     this.BeginInvoke(btnenable, button2, true);
                     this.BeginInvoke(btnenable, button1, true);
                     
                 }));
            thread.Start();
        }
        private float[] readTempValue(string conf) {
            if (selectItem.outtype == 2)
            {
                try {
                    return new float[2] { (float)(productmaster.ReadHoldingRegisters(Convert.ToByte(modbusConf.id), 1, 1)[0] / 10.0) , (float)(productmaster.ReadHoldingRegisters(Convert.ToByte(modbusConf.id), 1, 1)[0] / 10.0) };
                } catch (Exception e) {
                    testingRadio.BackColor = Color.AntiqueWhite;
                    MessageBoxEx.Show( "产品串口通讯异常！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button2);
                    return null;
                }              
            }
            else
            {
                try
                {
                    string tempstring = visaUtil.readAndconfig(Tempsession, conf);
                    float tempvalue = float.Parse(handlestring(tempstring), System.Globalization.NumberStyles.Float);
                    logHelper.WriteLog("温度测量测:" + tempvalue);
                    if (selectItem.outtype == 1)
                    {
                        return new float[2] { (float)(((tempvalue * 1000 - 4) * (selectItem.tempupper - selectItem.templower) / 16) + selectItem.templower), tempvalue*1000 };
                    }
                    else
                    {
                        return new float[2] {(float) ((tempvalue * (selectItem.tempupper - selectItem.templower) / float.Parse(selectItem.other, System.Globalization.NumberStyles.Float)) + selectItem.templower), tempvalue };
                    }
                }
                catch (Exception e) {
                    testingRadio.BackColor = Color.AntiqueWhite;
                    MessageBoxEx.Show( "温度万用表通讯异常！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button2);
                    return null;
                }

            }
        }
        private float[] readHumValue(string conf) {        
                float? hum = 0;
                if (selectItem.outtype == 2)
                {
                try { return new float[2] { (float)(productmaster.ReadHoldingRegisters(Convert.ToByte(modbusConf.id), 2, 1)[0] / 10.0), (float)(productmaster.ReadHoldingRegisters(Convert.ToByte(modbusConf.id), 2, 1)[0] / 10.0) }; } catch (Exception e) {
                    testingRadio.BackColor = Color.AntiqueWhite;
                    MessageBoxEx.Show(this, "产品串口通讯异常！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button2);
                    return null;
                }              
            }//rs485
                else {
                try
                {
                    string humstring = visaUtil.readAndconfig(HumSession, conf);//湿度测量
                    float humvalue = float.Parse(handlestring(humstring), System.Globalization.NumberStyles.Float);
                    logHelper.WriteLog("湿度测量测:"+ humvalue);
                    if (selectItem.outtype == 1)
                    {
                        return new float[2] { (float)(((humvalue * 1000 - 4) / 16 * (selectItem.humupper - selectItem.humlower)) + selectItem.humlower), humvalue*1000};
                    }
                    else {
                        return new float[2] { (float)((humvalue * (selectItem.humupper - selectItem.humlower) / float.Parse(selectItem.other, System.Globalization.NumberStyles.Float)) + selectItem.humlower), humvalue};
                    }
                }
            catch (Exception e1)
            {
                testingRadio.BackColor = Color.AntiqueWhite;
                MessageBoxEx.Show( "湿度万用表通讯异常！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button2);
                    return null;
                }
            }
                
         
        }
        private string handlestring(string visareturn)
        {
            if (visareturn.Contains(","))
            {
                return visareturn.Split(',')[0];
            }
            return visareturn;
        }




        private void bindCbox(int index)
        {
            IList<temphumProperty> properties = dao.SelectAllProperties();
            if (properties.Count > 0)
            {
                comboBox1.DataSource = properties;
                comboBox1.DisplayMember = "name";
                comboBox1.ValueMember = "id";
               
                comboBox1.SelectedIndex = index;
            }
            else {
                loadData(null);
            }
          
        }


        private void loadData(temphumProperty temphumProperty)
        {          
            if (temphumProperty != null)
            {
                numericUpDown2.Text =  Convert.ToString(temphumProperty.templower);
                numericUpDown3.Text =  Convert.ToString(temphumProperty.tempupper);
                numericUpDown29.Text =  Convert.ToString(temphumProperty.humlower);
                numericUpDown30.Text = Convert.ToString(temphumProperty.humupper);
               // numericUpDown9.Value = (Decimal)temphumProperty.temppoint;
              //  numericUpDown10.Value = (Decimal)temphumProperty.tempprecision;
                radioButton6.Checked = true;
             //   numericUpDown23.Value = (Decimal)temphumProperty.humpoint;
             //   numericUpDown24.Value = (Decimal)temphumProperty.humprecision;
                radioButton15.Checked = true;
                if (temphumProperty.outtype == 0)
                {
                    comboBox6.SelectedIndex = temphumProperty.other == "5" ? 0 : 1;
                    this.radioButton1.Checked = true;
                    comboBox6.Visible = true;
                    label9.Visible = true;
                }
                if (temphumProperty.outtype == 1)
                {
                    this.radioButton2.Checked = true;
                    comboBox6.Visible = false;
                    label9.Visible = false;
                }
                if (temphumProperty.outtype == 2)
                {
                    this.radioButton3.Checked = true;
                    comboBox6.Visible = false;
                    label9.Visible = false;
                }
                if (temphumProperty.producttype == 0)
                {
                    this.radioButton5.Checked = true;
                }
                else
                {
                    this.radioButton4.Checked = true;
                }
            }
            else {
                selectItem = new temphumProperty();
                numericUpDown2.Text ="";
                selectItem.templower = null;
                numericUpDown3.Text = "";
                selectItem.tempupper = null;
                numericUpDown29.Text = "";
                selectItem.humlower = null;
                numericUpDown30.Text = "";
                selectItem.humupper = null;
                radioButton6.Checked = true;
                radioButton15.Checked = true;
                this.radioButton1.Checked = true;
                this.radioButton5.Checked = true;
            }
          
            //button2.Enabled = false; 手动测试按钮置灰不可用

        }


        private void radioButton2_CheckedChanged(object sender, EventArgs e)
        {
            if (radioButton2.Checked)
            {
                if (selectItem == null)
                {
                    selectItem = new temphumProperty();
                }
                selectItem.outtype = 1;
                selectItem.other = "";
                // richTextBox8.Text = "";
                // richTextBox8.Visible = false;
                label10.Text = "mA";
                label12.Text = "mA";
                label9.Visible = false;
                comboBox6.Visible = false;
            }
        }



        private void statusStrip1_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
        {

        }
        private Boolean checkparam() {
            if (selectItem.producttype == 0) {
                Console.WriteLine(111);
             
                if (String.IsNullOrEmpty(Convert.ToString(selectItem.humupper)) || String.IsNullOrEmpty(Convert.ToString(selectItem.humlower))) return false;         
            }
            if (String.IsNullOrEmpty(Convert.ToString(selectItem.tempupper)) || String.IsNullOrEmpty(Convert.ToString(selectItem.templower))) return false;
            return true;
        }

        private void 参数ToolStripMenuItem_Click(object sender, EventArgs e)
        {
        }

        private void 另存为新参数ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (selectItem != null)
            {
                if (!checkparam())
                {
                    MessageBoxEx.Show("请检查参数！！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button2);
                    return;
                }
                this.selectItem.name = this.comboBox1.Text;
                this.selectItem.id = Guid.NewGuid().ToString();
                selectItem.createtime = DateTime.Now;
                dao.SaveProperty(this.selectItem);
                MessageBoxEx.Show( "创建成功！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button2);
                bindCbox(0);
            }
            else {
                MessageBoxEx.Show( "请检查参数！！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button2);
                return;
            }
            
        }

        private void radioButton5_CheckedChanged(object sender, EventArgs e)
        {
            if (radioButton5.Checked) {
                if (selectItem == null)
                {
                    selectItem = new temphumProperty();
                }
                this.selectItem.producttype = 0;
            }
        }

        private void radioButton4_CheckedChanged(object sender, EventArgs e)
        {
            if (radioButton4.Checked) {
                if (selectItem == null)
                {
                    selectItem = new temphumProperty();
                }
                this.selectItem.producttype = 1;
            }
          
        }

        private void 更新参数ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (selectItem != null)
            {
                if (!checkparam())
                {
                    MessageBoxEx.Show(this, "请检查参数！！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button2);
                    return;
                }
                Console.WriteLine("this.selectItem.name:" + this.selectItem.name);
                dao.updateProperty(this.selectItem);
                MessageBoxEx.Show( "更新成功！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button2);
                bindCbox(selectIndex);
            }
            else {
                MessageBoxEx.Show( "请检查参数！！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button2);
                return;
            }
            
        }
        private void validTextBox(string prop, RichTextBox textBox)
        {
            // if (textBox.Text != "") {
            if (double.TryParse(textBox.Text, out double ang) || int.TryParse(textBox.Text, out int angs))
            {
                selectItem.GetType().GetProperty(prop).SetValue(selectItem, float.Parse(textBox.Text));
            }
            else
            {
                selectItem.GetType().GetProperty(prop).SetValue(selectItem, null);
                // MessageBoxEx.Show(this, "请输入正确的值！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button2);
                //textBox.Text = "0";
            }
            //  }                      
        }

        private void 删除参数ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (selectItem != null)
            {
                dao.deleteProperty(this.selectItem);
                MessageBoxEx.Show( "删除成功！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button2);
                bindCbox(0);
            }
            else {
                MessageBoxEx.Show( "请选择后再删除！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button2);
                return;
            }
            
        }

        private void radioButton3_CheckedChanged(object sender, EventArgs e)
        {
            if (radioButton3.Checked)
            {
                if (selectItem == null)
                {
                    selectItem = new temphumProperty();
                }
                selectItem.outtype = 2;
                selectItem.other = "";
                //richTextBox8.Text = "";
                //  richTextBox8.Visible = false;
                label10.Text = "";
                label12.Text = "";
                label9.Visible = false;
                comboBox6.Visible = false;
            }
        }
        //初始化产品吗
        private void initProductCode()
        {
            codes = new Dictionary<string, string>();
            codeIndexes = new Dictionary<string, string>();
            int index = 0;
            for (char i = 'A'; i <= 'L'; i++)
            {
                for (int j = 1; j <= 8; j++)
                {
                    index++;
                    codeIndexes.Add(i + j.ToString(), index.ToString());
                    codes.Add(i + j.ToString(), "");
                }
            }
            for (var i = 0; i <= 95; i++) {
                radioStates[i] = false;
            }
            IList<temphumTestState> list = dao.findAllTestState();
            this.textBox5.Text = list.Count.ToString();
            if (list.Count > 0)
            {
                foreach (var i in list)
                {
                    var productIndex = codeIndexes.FirstOrDefault(c => c.Value == i.testport).Key;
                    codes[productIndex] = i.serialnumber;
                    Control[] controls = this.Controls.Find(productIndex, true);
                    if (controls.Count() > 0)
                    {
                        RadioButton selectRadio = (RadioButton)controls[0];
                        selectRadio.BackColor = System.Drawing.ColorTranslator.FromHtml(i.state);
                        if (i.serialnumber.Length > 3) { selectRadio.Text = i.testport + "/" + i.serialnumber.Substring(i.serialnumber.Length - 3, 3); } else { selectRadio.Text = i.testport; }                     
                    }

                }
            }
        }

        private void radioButton6_CheckedChanged(object sender, EventArgs e)
        {
            clickProductHandler((RadioButton)sender);
        }

        private void A6_CheckedChanged(object sender, EventArgs e)
        {
            clickProductHandler((RadioButton)sender);
        }

        private void label17_Click(object sender, EventArgs e)
        {

        }


        private void button3_Click(object sender, EventArgs e)
        {
            for (var i = 0; i < codes.Count; i++)
            {
                if (codes.ElementAt(i).Value != "")
                {
                  
                    Control[] controls = this.Controls.Find(codes.ElementAt(i).Key, true);
                    if (controls.Count() > 0)
                    {
                        RadioButton selectRadio = (RadioButton)controls[0];
                        codes[codes.ElementAt(i).Key] = "";
                        selectRadio.Checked = false;
                        selectRadio.Text = codeIndexes[codes.ElementAt(i).Key];
                        selectRadio.BackColor = Color.Gray;
                    }

                }
            }
            dao.deleteAllTestState();
            this.textBox5.Text = "0";
            MessageBoxEx.Show("清除成功！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button2);
        }

        private void J4_CheckedChanged(object sender, EventArgs e)
        {
            clickProductHandler((RadioButton)sender);
        }

        private void A2_CheckedChanged(object sender, EventArgs e)
        {
            clickProductHandler((RadioButton)sender);
        }
        private void clickProductHandler(RadioButton radioButton)
        {
            if (radioButton.Checked)
            {
                radioStates[int.Parse(codeIndexes[radioButton.Name]) - 1] = false;
                selectedCodeindex = Convert.ToUInt16(codeIndexes[radioButton.Name]);
                textBox2.Text = codeIndexes[radioButton.Name];
                textBox1.Text = codes[radioButton.Name];
                // ArrayList list = new ArrayList();
                // temphumHisData historydata = null;
                // if (textBox1.Text != "")
                // {
                //     pageLink link = new pageLink();
                //     link.serialnumber = textBox1.Text;
                //    long count = dao.findCountBySN(link);
                //     historydata = dao.findDataBySN(textBox1.Text);
                //     if (historydata != null)
                //     {
                //         historydata.testcount = count;
                //     }
                //}
                // if (historydata != null)
                // {
                //     list.Add(historydata);
                // }
                // else {
                //     list.Add(new temphumHisData());                                     
                // }
                // dataGridView1.DataSource = list;
                // if (dataGridView1.Columns.Contains("id"))
                // {
                //     dataGridView1.Columns["id"].Visible = false;
                // }
                // dataGridView1.Refresh();

            }
            else {
                radioStates[int.Parse(codeIndexes[radioButton.Name])-1] = false;
                selectedCodeindex = 0;
                textBox2.Text = "";
                textBox1.Text = "";
            }
        }

        private void A3_CheckedChanged(object sender, EventArgs e)
        {
            clickProductHandler((RadioButton)sender);
        }

        private void A4_CheckedChanged(object sender, EventArgs e)
        {
            clickProductHandler((RadioButton)sender);
        }

        private void A5_CheckedChanged(object sender, EventArgs e)
        {
            clickProductHandler((RadioButton)sender);
        }

        private void A8_CheckedChanged(object sender, EventArgs e)
        {
            clickProductHandler((RadioButton)sender);
        }

        private void B3_CheckedChanged(object sender, EventArgs e)
        {
            clickProductHandler((RadioButton)sender);
        }

        private void B2_CheckedChanged(object sender, EventArgs e)
        {
            clickProductHandler((RadioButton)sender);
        }

        private void B4_CheckedChanged(object sender, EventArgs e)
        {
            clickProductHandler((RadioButton)sender);
        }

        private void B5_CheckedChanged(object sender, EventArgs e)
        {
            clickProductHandler((RadioButton)sender);
        }

        private void B8_CheckedChanged(object sender, EventArgs e)
        {
            clickProductHandler((RadioButton)sender);
        }

        private void D2_CheckedChanged(object sender, EventArgs e)
        {
            clickProductHandler((RadioButton)sender);
        }

        private void C3_CheckedChanged(object sender, EventArgs e)
        {
            clickProductHandler((RadioButton)sender);
        }

        private void C4_CheckedChanged(object sender, EventArgs e)
        {
            clickProductHandler((RadioButton)sender);
        }

        private void C5_CheckedChanged(object sender, EventArgs e)
        {
            clickProductHandler((RadioButton)sender);
        }

        private void C8_CheckedChanged(object sender, EventArgs e)
        {
            clickProductHandler((RadioButton)sender);
        }

        private void C2_CheckedChanged(object sender, EventArgs e)
        {
            clickProductHandler((RadioButton)sender);
        }

        private void D3_CheckedChanged(object sender, EventArgs e)
        {
            clickProductHandler((RadioButton)sender);
        }

        private void D4_CheckedChanged(object sender, EventArgs e)
        {
            clickProductHandler((RadioButton)sender);
        }

        private void D5_CheckedChanged(object sender, EventArgs e)
        {
            clickProductHandler((RadioButton)sender);
        }

        private void D8_CheckedChanged(object sender, EventArgs e)
        {
            clickProductHandler((RadioButton)sender);
        }

        private void E8_CheckedChanged(object sender, EventArgs e)
        {
            clickProductHandler((RadioButton)sender);
        }

        private void F8_CheckedChanged(object sender, EventArgs e)
        {
            clickProductHandler((RadioButton)sender);
        }

        private void G8_CheckedChanged(object sender, EventArgs e)
        {
            clickProductHandler((RadioButton)sender);
        }

        private void H8_CheckedChanged(object sender, EventArgs e)
        {
            clickProductHandler((RadioButton)sender);
        }

        private void I8_CheckedChanged(object sender, EventArgs e)
        {
            clickProductHandler((RadioButton)sender);
        }

        private void K8_CheckedChanged(object sender, EventArgs e)
        {
            clickProductHandler((RadioButton)sender);
        }

        private void L8_CheckedChanged(object sender, EventArgs e)
        {
            clickProductHandler((RadioButton)sender);
        }

        private void F5_CheckedChanged(object sender, EventArgs e)
        {
            clickProductHandler((RadioButton)sender);
        }

        private void G2_CheckedChanged(object sender, EventArgs e)
        {
            clickProductHandler((RadioButton)sender);
        }

        private void L3_CheckedChanged(object sender, EventArgs e)
        {
            clickProductHandler((RadioButton)sender);
        }

        private void L4_CheckedChanged(object sender, EventArgs e)
        {
            clickProductHandler((RadioButton)sender);
        }

        private void L5_CheckedChanged(object sender, EventArgs e)
        {
            clickProductHandler((RadioButton)sender);
        }

        private void K2_CheckedChanged(object sender, EventArgs e)
        {
            clickProductHandler((RadioButton)sender);
        }

        private void J3_CheckedChanged(object sender, EventArgs e)
        {
            clickProductHandler((RadioButton)sender);
        }

        private void I4_CheckedChanged(object sender, EventArgs e)
        {
            clickProductHandler((RadioButton)sender);
        }

        private void I5_CheckedChanged(object sender, EventArgs e)
        {
            clickProductHandler((RadioButton)sender);
        }

        private void F3_CheckedChanged(object sender, EventArgs e)
        {
            clickProductHandler((RadioButton)sender);
        }

        private void F2_CheckedChanged(object sender, EventArgs e)
        {
            clickProductHandler((RadioButton)sender);
        }

        private void G3_CheckedChanged(object sender, EventArgs e)
        {
            clickProductHandler((RadioButton)sender);
        }

        private void H3_CheckedChanged(object sender, EventArgs e)
        {
            clickProductHandler((RadioButton)sender);
        }

        private void I3_CheckedChanged(object sender, EventArgs e)
        {
            clickProductHandler((RadioButton)sender);
        }

        private void H5_CheckedChanged(object sender, EventArgs e)
        {
            clickProductHandler((RadioButton)sender);
        }

        private void K5_CheckedChanged(object sender, EventArgs e)
        {
            clickProductHandler((RadioButton)sender);
        }

        private void K4_CheckedChanged(object sender, EventArgs e)
        {
            clickProductHandler((RadioButton)sender);
        }

        private void J2_CheckedChanged(object sender, EventArgs e)
        {
            clickProductHandler((RadioButton)sender);
        }

        private void H2_CheckedChanged(object sender, EventArgs e)
        {
            clickProductHandler((RadioButton)sender);
        }

        private void J5_CheckedChanged(object sender, EventArgs e)
        {
            clickProductHandler((RadioButton)sender);
        }

        private void E2_CheckedChanged(object sender, EventArgs e)
        {
            clickProductHandler((RadioButton)sender);
        }

        private void E3_CheckedChanged(object sender, EventArgs e)
        {
            clickProductHandler((RadioButton)sender);
        }

        private void F4_CheckedChanged(object sender, EventArgs e)
        {
            clickProductHandler((RadioButton)sender);
        }

        private void E4_CheckedChanged(object sender, EventArgs e)
        {
            clickProductHandler((RadioButton)sender);
        }

        private void E5_CheckedChanged(object sender, EventArgs e)
        {
            clickProductHandler((RadioButton)sender);
        }

        private void G4_CheckedChanged(object sender, EventArgs e)
        {
            clickProductHandler((RadioButton)sender);
        }

        private void H4_CheckedChanged(object sender, EventArgs e)
        {
            clickProductHandler((RadioButton)sender);
        }

        private void G5_CheckedChanged(object sender, EventArgs e)
        {
            clickProductHandler((RadioButton)sender);
        }

        private void button2_Click(object sender, EventArgs e)
        {
            logHelper.WriteLog("开始手动测试！");
            Console.WriteLine(selectItem.temppoint);
            this.BeginInvoke(btnenable, button1, false);
            this.BeginInvoke(btnenable, button2, false);
            if (!checkparam())
            {
                MessageBoxEx.Show("请检查参数！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button2);
                this.BeginInvoke(btnenable, button1, true);
                this.BeginInvoke(btnenable, button2, true);
                return;
            }
            Thread thread = new Thread(new ThreadStart(delegate {
                if (selectedCodeindex != 0)
                {
                    var productIndex = codeIndexes.FirstOrDefault(c => c.Value == selectedCodeindex.ToString()).Key;
                    this.BeginInvoke(update, selectedCodeindex+"",codes[productIndex],"端口" + selectedCodeindex + "----开始测试！");
                    Control[] controls = this.Controls.Find(productIndex, true);
                    RadioButton radioButton = (RadioButton)controls[0];
                    if (radioButton.Checked && codes[productIndex] != "")
                    {
                        temphumHisData historydata = new temphumHisData();
                        historydata.id = Guid.NewGuid().ToString();
                        historydata.serialnumber = codes[productIndex];
                        historydata.testport = selectedCodeindex.ToString();
                        historydata.producttype = selectItem.producttype;
                        historydata.temppoint = selectItem.temppoint;
                        if (selectItem.outtype == 0)
                        {
                            waitTime = volwaitTime;
                            historydata.testtype = "电压" + selectItem.other;
                        }
                        if (selectItem.outtype == 2)
                        {                  
                            historydata.testtype = "RS485";
                        }
                        if (selectItem.outtype == 1)
                        {
                            waitTime = curwaitTime;
                            historydata.testtype = "电流";
                        }
                        try
                        {
                            var readMsgReq = ModbusMessageFactory.CreateModbusRequest(modbusUtil.getSingleCoilMessage((short)selectedCodeindex, true));
                            // 获取响应报文
                            var writeSingleCoilsRes = boardmaster.ExecuteCustomMessage<WriteSingleCoilRequestResponse>(readMsgReq);
                            Thread.Sleep(waitTime);
                        }
                        catch (Exception e1)
                        {
                            MessageBoxEx.Show("请检查切换版通讯是否正常！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button2);
                            this.BeginInvoke(btnenable, button1, true);
                            this.BeginInvoke(btnenable, button2, true);
                            return;
                        }
                        testingRadio = (RadioButton)controls[0];
                        testingRadio.BackColor = Color.Blue;
                        Boolean isPass = true;
                        //    testingRadio.Refresh();
                        float[] sumTemp = new float[5];
                        float[] sumHum = new float[5];
                        float[] sumTempRead = new float[5];
                        float[] sumHumRead = new float[5];                      
                        for (int i = 1; i <= 5; i++)
                        {
                            string conf = "VOLT:DC " + selectItem.other;
                            if (selectItem.outtype == 1)
                            {
                                conf = "CURR:DC";
                            }
                            if (selectItem.producttype == 0)
                            { //温湿度类型

                                float[] hum = readHumValue(conf);
                              //  float[] hum = { 1.22f,2.4f};
                                if (hum == null)
                                {
                                    this.BeginInvoke(btnenable, button2, true);
                                    this.BeginInvoke(btnenable, button1, true);
                                    return;
                                };
                                Console.WriteLine("hum[1]:" + hum[1]);
                                sumHum[i-1] = hum[0];
                                sumHumRead[i-1] = hum[1];
                                this.BeginInvoke(humvalue, hum[1].ToString());
                            }
                           float[] temp = readTempValue(conf);
                            //float[] temp = { 1.22f, 2.4f };
                            if (temp == null)
                            {
                                this.BeginInvoke(btnenable, button2, true);
                                this.BeginInvoke(btnenable, button1, true);
                                return;
                            };
                            sumTemp[i-1] = temp[0];
                            sumTempRead[i-1] = temp[1];
                            Console.WriteLine("temp[1]:" + temp[1]);
                            this.BeginInvoke(tempvalue, temp[1].ToString());
                        }
                        Array.Sort(sumTemp);
                        Array.Sort(sumTempRead);
                        historydata.testtime = DateTime.Now;
                        historydata.tempread = sumTempRead[2];
                        historydata.temp = sumTemp[2];
                        historydata.tempdiv = (sumTemp[2]) - selectItem.temppoint;
                        if (Math.Abs((float)historydata.tempdiv) > selectItem.tempprecision) isPass = false;
                        if (selectItem.producttype == 0)
                        {
                            Array.Sort(sumHum);
                            Array.Sort(sumHumRead);
                            historydata.humpoint = selectItem.humpoint;
                            historydata.hum = sumHum[2];
                            historydata.humdiv = (sumHum[2]) - selectItem.humpoint;
                            historydata.humread = sumHumRead[2];
                            if (Math.Abs((float)historydata.humdiv) > selectItem.humprecision) isPass = false;
                        }
                        if (!isPass)
                        {
                            historydata.result = "NG";
                            testingRadio.BackColor = Color.Red;
                        }
                        else
                        {
                            historydata.result = "PASS";
                            testingRadio.BackColor = Color.Green;
                        }
                        ArrayList list = new ArrayList();
                        list.Add(historydata);
                        this.BeginInvoke(updateData,list);
                        dao.saveHistoryData(historydata);
                        saveProductState(testingRadio);//保存产品状态       
                        this.BeginInvoke(update, selectedCodeindex + "", codes[productIndex], "端口" + selectedCodeindex + "----结束测试！");
                        this.BeginInvoke(btnenable, button1, true);
                        this.BeginInvoke(btnenable, button2, true);
                    }
                    else
                    {
                        MessageBoxEx.Show("请绑定产品！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button2);
                        this.BeginInvoke(btnenable, button1, true);
                        this.BeginInvoke(btnenable, button2, true);
                    }
                }
                else
                {
                    MessageBoxEx.Show("请选择测试工位！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button2);
                    this.BeginInvoke(btnenable, button1, true);
                    this.BeginInvoke(btnenable, button2, true);
                }
            }));
            thread.Start();
        }

        private void 历史数据ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.Visible = false;
            testdata formdata = new testdata(this);
            formdata.Visible = true;
        }
        private void countBindPro() {
            int count = 0;
            foreach(var item in codes) {
                if (item.Value != "") {
                    count++;
                }
            }
            this.textBox5.Text = count.ToString();
        }
        private void richTextBox11_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == '\r')
            {
                if (textBox2.Text != "")
                {
                    int code = 100;
                    try
                    {
                        code = int.Parse(textBox2.Text);
                    }
                    catch (FormatException e3)
                    {
                        MessageBoxEx.Show("请检查端口码输入是否正确！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button2);
                        textBox2.Text = "";
                        return;
                    }
                    var productIndex = codeIndexes.FirstOrDefault(c => c.Value == code.ToString()).Key;
                    Control[] controls = this.Controls.Find(productIndex, true);
                    if (controls.Count() > 0)
                    {
                        if (textBox1.Text != "")
                        {
                            if (!Snparse(textBox1.Text)) {
                                MessageBoxEx.Show("请检查SN码输入是否正确！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button2);
                                return;
                            }
                            RadioButton selectRadio = (RadioButton)controls[0];
                            if (selectRadio.BackColor == Color.Yellow) {
                                MessageBoxEx.Show("此工位已绑定产品！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button2);
                                return;
                            }
                            var mapkey = codes.FirstOrDefault(c => c.Value == textBox1.Text).Key;
                            if (mapkey != null)
                            {
                                //codes[mapkey] = "";
                                //this.Controls.Find(mapkey, true)[0].BackColor = Color.Gray;
                                //dao.deleteTestStateByPort(mapkey);
                                MessageBoxEx.Show("输入的sn重复！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button2);
                                return;
                            }
                            codes[selectRadio.Name] = textBox1.Text;
                            selectRadio.BackColor = Color.Yellow;
                            selectRadio.Text = textBox2.Text + "/" + textBox1.Text.Substring(textBox1.Text.Length-3,3);
                            Console.WriteLine(selectRadio.Text);                         
                            saveProductState(selectRadio);
                            countBindPro();//更新已绑产品数量
                            selectRadio.Checked = false;
                            textBox1.Text = "";
                            textBox2.Text = "";
                        }
                        else { //输入为空解绑
                            codes[productIndex] = "";
                            this.Controls.Find(productIndex, true)[0].BackColor = Color.Gray;
                            this.Controls.Find(productIndex, true)[0].Text = textBox2.Text;
                            dao.deleteTestStateByPort(textBox2.Text);
                            countBindPro();//更新已绑产品数量
                        }
                       
                    }
                }
                else {
                    if (textBox1.Text != "")
                    {
                        var mapkey = codes.FirstOrDefault(c => c.Value == textBox1.Text).Key;
                        if (mapkey != null)
                        {
                            MessageBoxEx.Show("输入的sn重复！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button2);
                            return;
                        }
                        if (!Snparse(textBox1.Text))
                        {
                            MessageBoxEx.Show("请检查SN码输入是否正确！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button2);
                            textBox1.Text = "";
                            return;
                        }
                        textBox2.Focus();
                    }                
                }
            }
        }
        private void saveProductState(RadioButton r)
        {
            temphumTestState state = new temphumTestState();
            Console.WriteLine(textBox2.Text);
            Console.WriteLine(textBox1.Text);
            //state.testport = int.Parse(textBox2.Text).ToString();
            state.testport = int.Parse(codeIndexes[r.Name]).ToString();
           // state.serialnumber = textBox1.Text;
            state.serialnumber =codes[r.Name];
            state.state = r.BackColor.Name;
            state.statetime = DateTime.Now;
            dao.saveTestState(state);
        }
        private void richTextBox12_KeyPress(object sender, KeyPressEventArgs e)
        {

            if (e.KeyChar == '\r')
            {
                int code = 100;
                try {
                     code = int.Parse(textBox2.Text);
                } catch (FormatException e3) {
                    MessageBoxEx.Show("请检查端口码输入是否正确！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button2);
                    textBox2.Text = "";
                    return;
                }             
                var productIndex = codeIndexes.FirstOrDefault(c => c.Value == code.ToString()).Key;
                if (textBox1.Text != "")
                {
            
                    if (productIndex != null)
                    {
                        Control[] controls = this.Controls.Find(productIndex, true);
                        if (controls.Count() > 0)
                        {
                            RadioButton selectRadio = (RadioButton)controls[0];
                            if (selectRadio.BackColor == Color.Yellow)
                            {
                                MessageBoxEx.Show("此工位已绑定产品！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button2);
                                return;
                            }
                            var mapkey = codes.FirstOrDefault(c => c.Value == textBox1.Text).Key;
                            if (mapkey != null)
                            {
                                //codes[mapkey] = "";
                                //this.Controls.Find(mapkey, true)[0].BackColor = Color.Gray;
                                //dao.deleteTestStateByPort(mapkey);
                                MessageBoxEx.Show("输入的sn重复！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button2);
                                return;
                            }
                            codes[selectRadio.Name] = textBox1.Text;
                            selectRadio.BackColor = Color.Yellow;
                            selectRadio.Text = textBox2.Text + "/" + textBox1.Text.Substring(textBox1.Text.Length - 3, 3);
                            temphumTestState state = new temphumTestState();
                            state.testport = int.Parse(textBox2.Text).ToString();
                            state.serialnumber = textBox1.Text;
                            state.state = selectRadio.BackColor.Name;
                            state.statetime = DateTime.Now;
                            dao.saveTestState(state);
                            countBindPro();//更新已绑产品数量
                            textBox1.Text = "";
                            textBox2.Text = "";
                            textBox1.Focus();
                        }
                    }
                    else
                    {
                        MessageBoxEx.Show("请检查端口码输入是否正确！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button2);
                        textBox2.Text = "";
                    }

                }
                else {
                    if (productIndex == null)
                    {
                        MessageBoxEx.Show("请检查端口码输入是否正确！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button2);
                        textBox2.Text = "";
                    }
                    }
            }
        }

        private Boolean Snparse(String sn) {
            if (sn.Length < 11 || sn.Length > 12) return false;
            if (Convert.ToInt16(sn.Substring(0, 2)) != 80 && Convert.ToInt16(sn.Substring(0, 2)) != 90) return false;
            if (Convert.ToInt16(sn.Substring(0, 2)) == 80){
                if (selectItem.producttype != 0) return false;
            }
            if (Convert.ToInt16(sn.Substring(0, 2)) == 90) {
                if (selectItem.producttype != 1) return false;
            }
            return true;
        }

        private void richTextBox12_TextChanged(object sender, EventArgs e)
        {

        }

        private void menuStrip1_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
        {

        }

        private void comboBox2_SelectedIndexChanged(object sender, EventArgs e)
        {
          //  Console.WriteLine(comboBox2.SelectedItem);
        }
        private void comboBox2_DropDown(object sender, EventArgs e)
        {
            try
            {
                var resources = visaUtil.manager.Find("(ASRL|GPIB|TCPIP|USB)?*INSTR");
                comboBox2.Items.Clear();
                foreach (string s in resources)
                {
                    comboBox2.Items.Add(s);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }

        }
        private void comboBox3_DropDown(object sender, EventArgs e)
        {
            try
            {
                var resources = visaUtil.manager.Find("(ASRL|GPIB|TCPIP|USB)?*INSTR");
                comboBox3.Items.Clear();
                foreach (string s in resources)
                {
                    comboBox3.Items.Add(s);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }

        }

        private void button4_Click(object sender, EventArgs e)
        {
            if (comboBox2.SelectedItem != null)
            {
                if (button4.Text == "打开")
                {
                    try
                    {
                        HumSession = visaUtil.opensession(comboBox2.SelectedItem.ToString());                      
                       
                    }
                    catch (Exception e1)
                    {
                        MessageBoxEx.Show(this, "资源打开失败！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button2);
                        return;
                    }
                    try {
                        float tempvalue = float.Parse(handlestring(visaUtil.TestVisa(HumSession)), System.Globalization.NumberStyles.Float);
                        textBox4.Text = this.selectItem.outtype == 1 ? (tempvalue *1000).ToString() : tempvalue.ToString();
                        button4.BackColor = Color.Green;
                    } catch (Exception e2) {
                        button4.BackColor = Color.Red;
                    }
                    button4.Text = "关闭";
                    comboBox2.Enabled = false;
                }
                else
                {
                    if (HumSession != null)
                    {
                        visaUtil.closesession(HumSession);
                        button4.Text = "打开";
                        comboBox2.Enabled = true;
                        button4.BackColor = System.Drawing.SystemColors.Window;
                        textBox4.Text = "";
                    }
                }
            }
        }

        private void button5_Click(object sender, EventArgs e)
        {
            if (comboBox2.SelectedItem != null)
            {
                if (button5.Text == "打开")
                {
                    try { Tempsession = visaUtil.opensession(comboBox3.SelectedItem.ToString()); } catch (Exception e1) {
                        MessageBoxEx.Show("资源打开失败！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button2);
                        return;
                    }
                    try {
                        float humvalue = float.Parse(handlestring(visaUtil.TestVisa(Tempsession)), System.Globalization.NumberStyles.Float);
                        textBox3.Text = this.selectItem.outtype == 1 ? (humvalue * 1000).ToString() : humvalue.ToString();
                       // textBox3.Text = humvalue.ToString();
                        button5.BackColor = Color.Green;
                    } catch (Exception e2) {
                        button5.BackColor = Color.Red;
                    }
                    button5.Text = "关闭";
                    comboBox3.Enabled = false;
                }
                else
                {
                    if (Tempsession != null)
                    {
                        visaUtil.closesession(Tempsession);
                        button5.Text = "打开";
                        comboBox3.Enabled = true;
                        button5.BackColor = System.Drawing.SystemColors.Window;
                        textBox3.Text = "";
                    }
                }
            }
        }

        private void comboBox4_SelectedIndexChanged(object sender, EventArgs e)
        {

        }
        private void comboBox4_DropDown(object sender, EventArgs e)
        {
            comboBox4.Items.Clear();
            comboBox4.Items.AddRange(SerialPort.GetPortNames());
        }
        private void Form1Closing(object sender, EventArgs e)
        {
            this.Dispose();
        }

        private void button6_Click(object sender, EventArgs e)
        {
            if (button6.Text == "打开")
            {
                serialPort = modbusUtil.getSerialPort(comboBox4.SelectedItem.ToString());
                try
                {
                    serialPort.Open();
                    boardmaster = ModbusSerialMaster.CreateRtu(serialPort);
                    boardmaster.Transport.ReadTimeout = 1000;
                    button6.Text = "关闭";
                    comboBox4.Enabled = false;
                }
                catch (Exception e1)
                {
                    MessageBoxEx.Show(this, "端口打开失败！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button2);
                }
                try {
                  //  boardmaster.ReadHoldingRegisters(id, 1, 2);
                    var readMsgReq = ModbusMessageFactory.CreateModbusRequest(modbusUtil.testCom());
                    //获取响应报文
                    var writeSingleCoilsRes = boardmaster.ExecuteCustomMessage<ReadHoldingInputRegistersResponse>(readMsgReq);
                    button6.BackColor = Color.Green;               
                } catch (Exception e2) {
                    button6.BackColor = Color.Red;
                }

            }
            else
            {
                if (serialPort != null || serialPort.IsOpen)
                {
                    serialPort.Close();
                    boardmaster.Dispose();
                    button6.Text = "打开";
                    button6.BackColor = System.Drawing.SystemColors.Window;
                    comboBox4.Enabled = true;
                }
            }

        }

        private void comboBox3_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        private void combobox5_dropdown(object sender, EventArgs e)
        {
            comboBox5.Items.Clear();
            comboBox5.Items.AddRange(SerialPort.GetPortNames());
        }

        private void button7_Click(object sender, EventArgs e)
        {
            if (button7.Text == "打开")
            {
                modbusConf conf = new modbusConf();
                conf.ShowDialog();
                if (conf.DialogResult == DialogResult.OK)
                {
                    productserialPort = conf.serialPort;
                    productserialPort.PortName = comboBox5.SelectedItem.ToString();

                }
                else {
                    productserialPort = modbusUtil.getSerialPort(comboBox5.SelectedItem.ToString());
                    modbusConf.id = 1;
                }
                try
                {               
                    productserialPort.Open();
                    productmaster = ModbusSerialMaster.CreateRtu(productserialPort);
                    productmaster.Transport.ReadTimeout = 1000;
                    button7.Text = "关闭";
                    comboBox5.Enabled = false;
                }
                catch (Exception e1)
                {
                    MessageBoxEx.Show("端口打开失败！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button2);
                }
            }
            else
            {
                if (productserialPort != null || productserialPort.IsOpen)
                {
                    productserialPort.Close();
                    productmaster.Dispose();
                    button7.Text = "打开";
                    comboBox5.Enabled = true;
                }
            }
        }
        private void richTextBox3_validating(object sender, CancelEventArgs e)
        {
            NumericUpDown richTextBox = (NumericUpDown)sender;
            string errorMsg;
            if (selectItem.producttype == 0)
            {
                if (richTextBox.Text == "" || richTextBox.Text == null)
                {
                    errorMsg = "不能为空！";
                    e.Cancel = true;
                    richTextBox.Select(0, richTextBox.Text.Length);
                    this.errorProvider1.SetError(richTextBox, errorMsg);
                }
                else
                {
                    this.errorProvider1.Clear();
                }
            }

        }
        private void richTextBox2_validating(object sender, CancelEventArgs e)
        {
            NumericUpDown richTextBox = (NumericUpDown)sender;
            string errorMsg;
                if (richTextBox.Text == "" || richTextBox.Text == null)
                {
                    errorMsg = "不能为空！";
                    e.Cancel = true;
                    richTextBox.Select(0, richTextBox.Text.Length);
                    this.errorProvider1.SetError(richTextBox, errorMsg);
                }
                else
                {
                    this.errorProvider1.Clear();
                }
            

        }

        private void numericUpDown1_valuechanged(object sender, EventArgs e)
        {
        }
        private void up1_textChanged(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == '\r') {
                UpDownBase numeric = (UpDownBase)sender;
                if (selectItem == null)
                {
                    selectItem = new temphumProperty();
                }
                if (numeric.Text == "") {                  
                    selectItem.GetType().GetProperty("temppoint").SetValue(selectItem, null); }
                else { selectItem.GetType().GetProperty("temppoint").SetValue(selectItem, float.Parse(numeric.Text)); }

            }
        }
        private void up2_textChanged(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == '\r')
            {
                UpDownBase numeric = (UpDownBase)sender;
                if (selectItem == null)
                {
                    selectItem = new temphumProperty();
                }
                if (numeric.Text == "") { selectItem.GetType().GetProperty("templower").SetValue(selectItem, null); }
                else { selectItem.GetType().GetProperty("templower").SetValue(selectItem, float.Parse(numeric.Text)); }
            }         
        }
        private void up3_textChanged(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == '\r')
            {
                UpDownBase numeric = (UpDownBase)sender;
                if (selectItem == null)
                {
                    selectItem = new temphumProperty();
                }
                if (numeric.Text == "") { selectItem.GetType().GetProperty("tempupper").SetValue(selectItem, null); }
                else { selectItem.GetType().GetProperty("tempupper").SetValue(selectItem, float.Parse(numeric.Text)); }
            }         
        }
        private void up4_textChanged(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == '\r')
            {
                UpDownBase numeric = (UpDownBase)sender;
                if (selectItem == null)
                {
                    selectItem = new temphumProperty();
                }
                if (numeric.Text == "") { selectItem.GetType().GetProperty("tempprecision").SetValue(selectItem, null); }
                else { selectItem.GetType().GetProperty("tempprecision").SetValue(selectItem, float.Parse(numeric.Text)); }
            }    
        }
        private void up5_textChanged(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == '\r')
            {
                UpDownBase numeric = (UpDownBase)sender;
                if (selectItem == null)
                {
                    selectItem = new temphumProperty();
                }
                if (numeric.Text == "") { selectItem.GetType().GetProperty("humpoint").SetValue(selectItem, null); }
                else { selectItem.GetType().GetProperty("humpoint").SetValue(selectItem, float.Parse(numeric.Text)); }
            }
        }
        private void up6_textChanged(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == '\r')
            {
                UpDownBase numeric = (UpDownBase)sender;
                if (selectItem == null)
                {
                    selectItem = new temphumProperty();
                }
                if (numeric.Text == "") { selectItem.GetType().GetProperty("humlower").SetValue(selectItem, null); }
                else { selectItem.GetType().GetProperty("humlower").SetValue(selectItem, float.Parse(numeric.Text)); }
            }      
        }
        private void up7_textChanged(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == '\r')
            {
                UpDownBase numeric = (UpDownBase)sender;
                if (selectItem == null)
                {
                    selectItem = new temphumProperty();
                }
                if (numeric.Text == "") { selectItem.GetType().GetProperty("humupper").SetValue(selectItem, null); }
                else { selectItem.GetType().GetProperty("humupper").SetValue(selectItem, float.Parse(numeric.Text)); }
            }
        }
        private void up8_textChanged(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == '\r')
            {
                UpDownBase numeric = (UpDownBase)sender;
                if (selectItem == null)
                {
                    selectItem = new temphumProperty();
                }
                if (numeric.Text == "") { selectItem.GetType().GetProperty("humprecision").SetValue(selectItem, null); }
                else { selectItem.GetType().GetProperty("humprecision").SetValue(selectItem, float.Parse(numeric.Text)); }
            }
        }

        private void statusStrip1_ItemClicked_1(object sender, ToolStripItemClickedEventArgs e)
        {

        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            this.toolStripStatusLabel3.Text = "系统时间：" + DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss");
        }

        private void comboBox6_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (this.selectItem == null)
            {
                this.selectItem = new temphumProperty();
            }
            this.selectItem.other = comboBox6.SelectedIndex == 0 ? "5" : "10";
        }

        private void checkBox1_CheckedChanged(object sender, EventArgs e)
        {

        }

        private void label5_Click(object sender, EventArgs e)
        {

        }


        private void radioButton6_CheckedChanged_1(object sender, EventArgs e)
        {
            if (radioButton6.Checked)
            { TempRadioControl(9, 10); }
        }
        private void TempRadioControl(int j,int k) {
            if (this.selectItem == null)
            {
                this.selectItem = new temphumProperty();
            }
            for (int i = 9; i <= 18; i++) {
                Control[] controls = this.Controls.Find("numericUpDown" + i.ToString(), true);
                NumericUpDown numeric =(NumericUpDown)controls[0];
                if (j == i)
                {
                    numeric.Enabled = false;
                    selectItem.temppoint = (float)numeric.Value;
                    Console.WriteLine(" selectItem.temppoint :"+selectItem.temppoint);
                    continue;
                }
                if (k == i) {
                    numeric.Enabled = false;
                    selectItem.tempprecision = (float)numeric.Value;
                    Console.WriteLine(" selectItem.tempprecision :" + selectItem.tempprecision);
                    continue;
                }
                    numeric.Enabled = true;
            }
        }
        private void HumRadioControl(int j, int k)
        {
            if (this.selectItem == null)
            {
                this.selectItem = new temphumProperty();
            }
            for (int i = 19; i <= 24; i++)
            {
                Control[] controls = this.Controls.Find("numericUpDown" + i.ToString(), true);
                NumericUpDown numeric = (NumericUpDown)controls[0];
                if (j == i)
                {
                    numeric.Enabled = false;
                    selectItem.humpoint = (float)numeric.Value;
                    Console.WriteLine(" selectItem.temppoint :" + selectItem.humpoint);
                    continue;
                }
                if (k == i)
                {
                    numeric.Enabled = false;
                    selectItem.humprecision = (float)numeric.Value;
                    Console.WriteLine(" selectItem.humprecision :" + selectItem.humprecision);
                    continue;
                }
                numeric.Enabled = true;
            }
        }

        private void radioButton10_CheckedChanged(object sender, EventArgs e)
        {
            if (radioButton10.Checked) { TempRadioControl(18, 17); }
                       
        }

        private void numericUpDown9_Leave(object sender, KeyEventArgs e)
        {
            if (numericUpDown9.Text == "")
            {
                radioButton6.Enabled = false;
                return;
            }
            radioButton6.Enabled = true;
        }

        private void numericUpDown10_KeyUp(object sender, KeyEventArgs e)
        {
            if (numericUpDown10.Text == "")
            {
                radioButton6.Enabled = false;
                return;
            }
            radioButton6.Enabled = true;
        }

        private void numericUpDown18_KeyUp(object sender, KeyEventArgs e)
        {
            if (numericUpDown18.Text == "")
            {
                radioButton10.Enabled = false;
                return;
            }
            radioButton10.Enabled = true;
        }

        private void numericUpDown17_KeyUp(object sender, KeyEventArgs e)
        {
            if (numericUpDown17.Text == "")
            {
                radioButton10.Enabled = false;
                return;
            }
            radioButton10.Enabled = true;
        }

        private void radioButton7_CheckedChanged(object sender, EventArgs e)
        {
            if (radioButton7.Checked) { TempRadioControl(12, 11); }          
        }

        private void radioButton8_CheckedChanged(object sender, EventArgs e)
        {
            if (radioButton8.Checked)
            { TempRadioControl(14, 13); }
        }

        private void radioButton9_CheckedChanged(object sender, EventArgs e)
        {
            if (radioButton9.Checked)
            { TempRadioControl(16, 15); }
        }

        private void numericUpDown12_KeyUp(object sender, KeyEventArgs e)
        {
            if (numericUpDown12.Text == "")
            {
                radioButton7.Enabled = false;
                return;
            }
            radioButton7.Enabled = true;
        }

        private void numericUpDown11_KeyUp(object sender, KeyEventArgs e)
        {
            if (numericUpDown11.Text == "")
            {
                radioButton7.Enabled = false;
                return;
            }
            radioButton7.Enabled = true;
        }

        private void numericUpDown14_KeyUp(object sender, KeyEventArgs e)
        {
            if (numericUpDown14.Text == "")
            {
                radioButton8.Enabled = false;
                return;
            }
            radioButton8.Enabled = true;
        }

        private void numericUpDown13_KeyUp(object sender, KeyEventArgs e)
        {
            if (numericUpDown13.Text == "")
            {
                radioButton8.Enabled = false;
                return;
            }
            radioButton8.Enabled = true;
        }

        private void radioButton15_CheckedChanged(object sender, EventArgs e)
        {
            if (radioButton15.Checked) { HumRadioControl(23,24); }
        }

        private void radioButton13_CheckedChanged(object sender, EventArgs e)
        {
            if (radioButton13.Checked) { HumRadioControl(21, 22); }
        }

        private void radioButton11_CheckedChanged(object sender, EventArgs e)
        {
            if (radioButton11.Checked) { HumRadioControl(20, 19); }
        }

        private void numericUpDown23_KeyUp(object sender, KeyEventArgs e)
        {
            if (numericUpDown23.Text == "")
            {
                radioButton15.Enabled = false;
                return;
            }
            radioButton15.Enabled = true;
        }

 
        private void numericUpDown21_KeyUp(object sender, KeyEventArgs e)
        {
            if (numericUpDown21.Text == "")
            {
                radioButton13.Enabled = false;
                return;
            }
            radioButton13.Enabled = true;
        }

        private void numericUpDown22_KeyUp(object sender, KeyEventArgs e)
        {
            if (numericUpDown22.Text == "")
            {
                radioButton13.Enabled = false;
                return;
            }
            radioButton13.Enabled = true;
        }

        private void numericUpDown20_KeyUp(object sender, KeyEventArgs e)
        {
            if (numericUpDown20.Text == "")
            {
                radioButton11.Enabled = false;
                return;
            }
            radioButton11.Enabled = true;
        }

        private void numericUpDown19_KeyUp(object sender, KeyEventArgs e)
        {
            if (numericUpDown19.Text == "")
            {
                radioButton11.Enabled = false;
                return;
            }
            radioButton11.Enabled = true;
        }

        private void numericUpDown24_ValueChanged(object sender, KeyEventArgs e)
        {
            if (numericUpDown24.Text == "")
            {
                radioButton15.Enabled = false;
                return;
            }
            radioButton15.Enabled = true;
        }

        private void numericUpDown29_ValueChanged(object sender, EventArgs e)
        {

        }

        private void numericUpDown29_KeyPress(object sender, KeyPressEventArgs e)
        {
                if (e.KeyChar == '\r')
                {
                    UpDownBase numeric = (UpDownBase)sender;
                    if (selectItem == null)
                    {
                        selectItem = new temphumProperty();
                    }
                    if (numeric.Text == "") { selectItem.GetType().GetProperty("humlower").SetValue(selectItem, null); }
                    else { selectItem.GetType().GetProperty("humlower").SetValue(selectItem, float.Parse(numeric.Text)); }
                }
        }

        private void numericUpDown30_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == '\r')
            {
                UpDownBase numeric = (UpDownBase)sender;
                if (selectItem == null)
                {
                    selectItem = new temphumProperty();
                }
                if (numeric.Text == "") { selectItem.GetType().GetProperty("humupper").SetValue(selectItem, null); }
                else { selectItem.GetType().GetProperty("humupper").SetValue(selectItem, float.Parse(numeric.Text)); }
            }
        }
        private bool rbcheck = true;
        private void D4_Click(object sender, EventArgs e)
        {
            Console.WriteLine(111111111);
            RadioButton r = (RadioButton)sender;
            Boolean isChecked = radioStates[int.Parse(codeIndexes[r.Name])-1];
            Console.WriteLine(isChecked);
            Console.WriteLine(codeIndexes[r.Name]);
            if (isChecked)
            {
                Console.WriteLine(2222222);
                r.Checked = false;
                radioStates[int.Parse(codeIndexes[r.Name])-1] = false;
            }
            else {
                radioStates[int.Parse(codeIndexes[r.Name])-1] = true;
                r.Checked = true;
            }
          
        }

        private void comboBox1_DropDown(object sender, EventArgs e)
        {

           
        }

        private void Form1_Resize(object sender, EventArgs e)
        {
            float newx = this.Width / X;
            float newy = this.Height / Y;
            if (this != null) {
                ResizeForm.setControls(newx, newy, this);
            }
           // ResizeForm.setControls(newx, newy, this);
        }

        private void dataGridView1_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
        {
                if (e.RowIndex > -1)
                {
                    String result = dataGridView1.Rows[e.RowIndex].Cells["测试结果"].Value.ToString();
                    if (result == "NG")
                    {
                        this.dataGridView1.Rows[e.RowIndex].Cells["测试结果"].Style.BackColor = Color.Red;
                    }
                    else
                    {
                        this.dataGridView1.Rows[e.RowIndex].Cells["测试结果"].Style.BackColor = Color.Green;
                    }
                }

        }

        private void numericUpDown4_ValueChanged(object sender, EventArgs e)
        {
            volwaitTime = (int)numericUpDown4.Value * 1000;
           Console.WriteLine(volwaitTime);
        }

        private void numericUpDown5_ValueChanged(object sender, EventArgs e)
        {
            curwaitTime = (int)numericUpDown5.Value * 1000;
            Console.WriteLine(curwaitTime);
        }
    }
    }
